<template>
  <!-- 品牌管理 -->
  <div class="main-container">
    <el-card shadow="hover">
      <div slot="header" class="clearfix">
        <el-button type="primary" icon="el-icon-plus" @click="addBrand"
          >添加</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table border stripe :data="BrandListByPage">
        <el-table-column
          label="序号"
          type="index"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="品牌名称"
          prop="tmName"
          align="center"
        ></el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="editBrand(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteBrand(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 15]"
        @current-change="currentPageChange"
        @size-change="pageSizeChange"
        layout="prev,pager,sizes,total,->,jumper"
      ></el-pagination>
    </el-card>

    <!-- Dialog对话框 -->
    <el-dialog :title="DialogTitle" :visible.sync="dialogVisible">
      <el-form
        label-width="150px"
        :rules="rules"
        :model="addOrEditBrandParm"
        ref="ruleForm"
      >
        <el-form-item label="品牌名称" prop="tmName"
          ><el-input type="text" v-model="addOrEditBrandParm.tmName"></el-input
        ></el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload
            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="uploadSuccess"
          >
            <img
              v-if="addOrEditBrandParm.logoUrl"
              :src="addOrEditBrandParm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureToAddOrEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqBrandListByPage,
  reqAddBrand,
  reqUpdateBrand,
  reqDeleteBrand,
} from "@/api/brand";
import { Message } from "element-ui";
export default {
  name: "Brand",
  data() {
    //规则1:tmName校验
    const validateTmName = (rules, value, cb) => {
      if (value.length >= 2 && value.length <= 10) {
        cb();
      } else {
        cb(new Error("品牌名称长度必须2-10之间"));
      }
    };
    return {
      //数据1:品牌列表(分页)
      BrandListByPage: [],
      //数据2:品牌总条数
      total: 0,
      //数据3:当前页
      currentPage: 1,
      //数据4:每页条数
      pageSize: 5,
      //数据5:总页数
      totalPage: 0,
      //数据6:Dialog对话框title
      DialogTitle: "",
      //数据7:控制Dialog显示隐藏
      dialogVisible: false,
      //数据8:添加品牌参数
      addOrEditBrandParm: {
        tmName: "",
        logoUrl: "",
      },
      //数据9:dialog表单校验规则
      rules: {
        tmName: [
          {
            required: true,
            message: "请输入品牌名",
            trigger: "blur",
            validator: validateTmName,
          },
        ],
        logoUrl: [
          { required: true, message: "必须上传图片", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    //方法1:请求品牌列表(分页)数据
    async getBrandListByPageInfo() {
      try {
        const result = await reqBrandListByPage(
          this.currentPage,
          this.pageSize
        );
        this.total = result.data.total;
        this.currentPage = result.data.current;
        this.pageSize = result.data.size;
        this.totalPage = result.data.pages;
        this.BrandListByPage = result.data.records;
        console.log("请求品牌列表(分页)数据", result);
      } catch (e) {
        console.log("请求品牌列表(分页)失败");
      }
    },
    //方法2:当前页改变事件
    currentPageChange(v) {
      this.currentPage = v;
      this.getBrandListByPageInfo();
    },
    //方法3:每页条数改变事件
    pageSizeChange(v) {
      this.pageSize = v;
      this.getBrandListByPageInfo();
    },
    //方法4:添加(品牌)按钮点击事件
    async addBrand() {
      //对话框显示
      this.dialogVisible = true;
      this.DialogTitle = "添加品牌";
      //清空上次添加或修改遗留的数据
      this.addOrEditBrandParm = {
        tmName: "",
        logoUrl: "",
      };
      //清除上次表单校验 的遗留
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    //方法5:上传图片成功时触发
    uploadSuccess(response, file, fileList) {
      console.log("response", response);
      console.log("file", file);
      console.log("fileList", fileList);
      this.addOrEditBrandParm.logoUrl = response.data;
    },
    //方法6:dialog确定按钮
    async sureToAddOrEdit() {
      try {
        //表单校验
        await this.$refs.ruleForm.validate();
        //判断是修改逻辑还是添加逻辑
        if (this.DialogTitle === "添加品牌") {
          //添加逻辑
          try {
            await reqAddBrand(this.addOrEditBrandParm);
            this.dialogVisible = false;
            this.currentPage = Math.ceil((this.total + 1) / this.pageSize);
            await this.getBrandListByPageInfo(this.currentPage, this.pageSize);
            Message.success("添加成功");
          } catch (e) {
            Message.error("添加失败");
          }
        } else {
          //修改逻辑
          try {
            await reqUpdateBrand(this.addOrEditBrandParm);
            this.dialogVisible = false;
            this.getBrandListByPageInfo();
            Message.success("修改成功");
          } catch (e) {
            Message.error("修改失败");
          }
        }
      } catch (e) {
        Message.error("校验失败");
      }
    },
    //方法7:修改品牌按钮点击事件
    async editBrand(row) {
      //dialog显示
      this.dialogVisible = true;
      //dialog的标题改为修改品牌
      this.DialogTitle = "修改品牌";
      console.log("row", row);
      //将点击的这一行的数据保存 填充进表单
      this.addOrEditBrandParm.id = row.id;
      this.addOrEditBrandParm.logoUrl = row.logoUrl;
      this.addOrEditBrandParm.tmName = row.tmName;
    },
    //方法8:删除品牌按钮点击事件
    deleteBrand(row) {
      this.$confirm(`你确定要删除${row.tmName}吗?`, "注意", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //确定逻辑
          console.log("确定删除");
          try {
            //发送删除请求
            await reqDeleteBrand(row.id);
            //判断当前页是不是唯一的数据
            this.currentPage =
              this.BrandListByPage.length == 1
                ? this.currentPage - 1
                : this.currentPage;
            //重新发送分页请求
            this.getBrandListByPageInfo(this.currentPage, this.pageSize);
          } catch (e) {
            Message.error("删除失败");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted() {
    //初始化1:请求品牌列表(分页)数据
    this.getBrandListByPageInfo();
  },
};
</script>

<style scoped>
.main-container {
  padding: 20px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 480px;
}

/* upload */
.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
}
.avatar-uploader .avatar {
  border: 1px dashed #d9d9d9;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
